<template>
  <transition name="logbox">
    <div class="auth-modal-box" v-if="logboxshow">
      <div class="auth-form">
        <div class="panda" v-show="this.islog">
          <img src="./img/normal.0447fe9.png" alt="" v-show="this.panda == 1">
          <img src="./img/greeting.1415c1c.png" alt="" v-show="this.panda == 2">
          <img src="./img/blindfold.58ce423.png" alt="" v-show="this.panda == 3">
        </div>
        <i class="iconfont close-btn" @click="hide" title="关闭"></i>
        <div class="panel" v-if="this.islog">
          <p class="title">登录</p>
          <div class="input-group">
            <div class="input-box">
              <input
                type="text"
                placeholder="请输入手机号或邮箱"
                maxlength="64"
                class="input"
                @focus="pandaChange (2)"
                @blur="pandaChange (1)"
                v-model="login_con.phoneEmail"
                ref="logPhone"
              >
            </div>
            <div class="input-box">
              <input
                type="password"
                placeholder="请输入密码"
                class="input"
                @focus="pandaChange (3)"
                @blur="pandaChange (1)"
                v-model="login_con.password"
                ref="logPassword"
              >
            </div>
          </div>
          <button class="submit" @click="login">登录</button>
          <div class="prompt-box">
            没有账号？
            <span class="clickable" @click="show(false)">注册</span>
            <a href="/" class="clickable right">忘记密码</a>
          </div>
        </div>

        <div class="panel" v-else>
          <p class="title">注册</p>
          <div class="input-group">
            <div class="input-box">
              <input
                type="text"
                placeholder="请输入用户名"
                maxlength="20"
                class="input"
                v-model="reg_con.username"
                ref="regUsername"
              >
            </div>
            <div class="input-box">
              <input
                type="text"
                placeholder="请输入手机号"
                maxlength="20"
                class="input"
                v-model="reg_con.phoneNumber"
                ref="regPhone"
              >
            </div>
            <div class="input-box vcode-box" v-show="vcodeShow">
              <input
                type="text"
                class="input"
                placeholder="验证码"
                v-model="reg_con.imgVcodeCon"
                ref="regImgVcode"
                maxlength="4"
              >
              <div class="vcode-img" @click="changeImgVcode">
                模拟验证码：{{this.reg_con.imgVcode}}
              </div>
            </div>
            <div class="input-box" v-show="vcodeShow">
              <input
                type="text"
                class="input"
                placeholder="手机验证码"
                maxlength="4"
                v-model="reg_con.phoneVcodeCon"
                ref="regPhoneVcode"
              >
              <button
                class="send-vcode-btn"
                @click="getPhoneVcode"
                v-html="this.reg_con.getPhoneVcodeCon"
                :class="{action: reg_con.getPhoneVcodeBtnCss}"
              >
              </button>
            </div>
            <div class="input-box">
              <input
                type="password"
                placeholder="请输入密码（不少于6位）"
                class="input"
                v-model="reg_con.password"
                ref="regPassword"
              >
            </div>
          </div>
          <button class="submit" @click="register">注册</button>
          <div class="prompt-box center">
            <span class="clickable" @click="show(true)">已有账号登录</span>
          </div>
        </div>
        <div class="oauth-box">
          <div class="oauth-box">第三方账号登录：</div>
          <button class="oauth-btn iconfont" @click="QQlogin">使用QQ账号登录</button>
        </div>
      </div>
      <!-- <div class="errorBox" :class="{show: this.reg_con.state,succ: this.reg_con.stateSucc}" v-text="this.reg_con.errorText"></div> -->
      <div class="ajaxErrorBox" v-html="this.ajaxErrorText"></div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      logboxshow: false, // 控制登录框是否显示
      islog: true, // 判断需要显示登录框还是注册框
      panda: 1, // 控制熊猫图片切换 1、默认 2、输账号时 3、输密码时
      vcodeShow: false, // 控制验证码输入框的显示
      ajaxErrorText: '', // 显示后台返回错误信息
      qqLoginInterval: null,
      qqLogUrl: 'https://graph.qq.com/oauth2.0/authorize?response_type=token&client_id=101525230&redirect_uri=http%3A%2F%2Fshiliqingshan.com%2Fweb%2Fphp%2Fqqlogin.html&scope=all',
      login_con: { // 登录相关
        phoneEmail: '', // 手机或者邮箱
        password: ''
      },
      reg_con: { // 注册相关
        username: '', // 注册用户名
        phoneNumber: '', // 注册手机号码
        imgVcodeCon: '', // 注册图形验证码
        phoneVcodeCon: '', // 注册手机验证码
        password: '', // 注册密码
        getPhoneVcodeBtnCss: false, // 控制获取手机验证码按钮的外观以及是否可点击
        getPhoneVcodeCon: '获取验证码', // 控制获取手机验证码按钮的内容
        imgVcode: '', // 客户端模拟图片验证码
        phoneVcode: '' // 客户端模拟手机验证码
      }
    }
  },
  methods: {
    show (d) { // 显示登录框
      this.logboxshow = true
      this.islog = d
      let timer
      clearTimeout(timer)
      if (d) {
        timer = setTimeout(() => {
          this.$refs.logPhone.focus()
        }, 16)
      } else {
        timer = setTimeout(() => {
          this.$refs.regUsername.focus()
        }, 16)
      }
      document.onkeydown = this.$options.methods.keyDown.bind(this)
      this.$store.dispatch('changeState', {
        name: 'changeFilterBlur',
        value: true
      })
    },
    hide () { // 隐藏登录框
      this.logboxshow = false
      document.onkeydown = null
      this.$store.dispatch('changeState', {
        name: 'changeFilterBlur',
        value: false
      })
      this.$store.state.showLogBox = false
    },
    keyDown () {
      var key = window.event.keyCode
      if (key === 13) {
        if (this.islog) {
          this.$options.methods.login.apply(this)
        } else {
          this.$options.methods.register.apply(this)
        }
      }
    },
    pandaChange (n) { // 登录框上方熊猫图片变更
      this.panda = n
    },
    QQlogin () { // QQ登录
      // 判断是否是手机页面，如果是手机页面则跳转，如果是电脑则打开新窗口
      let userAgentInfo = navigator.userAgent
      let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
      let isPhone = false
      for (let v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
          isPhone = true
        }
      }
      if (isPhone) {
        window.location.href = this.qqLogUrl
      } else {
        window.open(this.qqLogUrl, 'newwindow', 'height=510, width=740')
        this.qqLoginInterval = setInterval(() => {
          this.$ajax({
            method: 'post',
            url: '/web/php/checkQQ.php'
          }).then((result) => {
            // 创建定时器不停的向服务器发送请求判断QQ登录结果
            this.ajaxErrorText = result.data
            if (result.data) {
              clearInterval(this.qqLoginInterval) // 接收到数据之后清除定时器
              this.hide()
              if (result.data === 10030) { // 根据返回结果进行不同操作 10001：登录成功 10002未绑定账号
                this.$store.dispatch('changeState', {
                  name: 'changeLoginState',
                  value: true
                })
              } else if (result.data === 10032) {
                this.$router.push('/bindqq')
              }
            }
          })
        }, 500)
      }
    },
    changeImgVcode () { // 改变图形验证码
      this.reg_con.imgVcode = Math.floor(Math.random() * 9000 + 1000)
    },
    // showRegError (data, _this, cssName = false) { // 显示错误提示框
    //   clearTimeout(_this.reg_con.errorTimeOut)
    //   _this.reg_con.stateSucc = cssName// 控制显示框样式
    //   _this.reg_con.state = true
    //   _this.reg_con.errorText = data
    //   _this.reg_con.errorTimeOut = setTimeout(() => {
    //     _this.reg_con.state = false
    //   }, 3000)
    // },
    getPhoneVcode () {
      if (this.reg_con.getPhoneVcodeBtnCss) return
      let _this = this
      this.$refs.regPhoneVcode.focus()
      let pathPhone = /^1[34578]\d{9}$/
      if (!pathPhone.test(this.reg_con.phoneNumber)) {
        this.common.showRegError('手机号码格式有误', _this)
        this.$refs.regPhone.focus()
        this.reg_con.phoneNumber = ''
        return false
      }
      let phoneVcode = Math.floor(Math.random() * 9000 + 1000)
      this.reg_con.phoneVcode = phoneVcode
      if (parseInt(this.reg_con.imgVcodeCon) !== this.reg_con.imgVcode) {
        this.common.showRegError('图形验证码填写错误', _this)
        this.$refs.regImgVcode.focus()
        this.reg_con.imgVcodeCon = ''
      } else {
        this.common.showRegError('本次模拟手机验证码为：' + phoneVcode, _this, true)
        this.$options.methods.changeImgVcode.apply(this)
        this.reg_con.getPhoneVcodeBtnCss = true
        let time = 5
        this.reg_con.getPhoneVcodeCon = time + ' 秒后重试'
        let timer = setInterval(() => {
          time--
          this.reg_con.getPhoneVcodeCon = time + ' 秒后重试'
          if (time <= 0) {
            this.reg_con.getPhoneVcodeCon = '获取验证码'
            this.reg_con.getPhoneVcodeBtnCss = false
            clearInterval(timer)
          }
        }, 1000)
      }
    },
    login () { // 登录事件
      let _this = this
      /** 验证用户名 */
      if (this.login_con.phoneEmail === '') {
        this.common.showRegError('请输入手机号或者邮箱', _this)
        this.$refs.logPhone.focus()
        this.login_con.phoneEmail = ''
        return false
      }
      /** 验证密码 */
      if (this.login_con.password === '') {
        this.common.showRegError('请输入密码', _this)
        this.$refs.logPassword.focus()
        this.login_con.password = ''
        return false
      }
      /** 向服务器发送登录请求 */
      this.$ajax({
        method: 'post',
        url: '/web/php/login.php',
        data: this.$qs.stringify({
          username: this.login_con.phoneEmail,
          password: this.login_con.password
        })
      }).then((data) => {
        console.log(data)
        let result = data.data
        let returnCode = result.returnCode
        let dataInfo = result.dataInfo
        switch (returnCode) {
          case 10000: // 登录成功
            this.login_con.phoneEmail = ''
            this.login_con.password = ''
            window.location.reload()
            // this.hide()
            // this.$store.dispatch('changeState', {
            //   name: 'changeLoginState',
            //   value: true
            // })
            break
          case 10001: // 用户名不能为空
            this.$refs.logPhone.focus()
            break
          case 10002: // 密码不能为空
            this.$refs.logPassword.focus()
            break
          case 10003: // 找不到该用户
            this.$refs.logPhone.focus()
            break
          case 10004: // 密码错误
            this.$refs.logPassword.focus()
            break
        }
        if (dataInfo) {
          if (returnCode === 10000) {
            this.common.showRegError(dataInfo, _this, true)
          } else {
            this.common.showRegError(dataInfo, _this)
          }
        }
      })
    },
    register () { // 注册事件
      let _this = this
      /** 验证用户名 */
      let pathUsername = /^[A-Za-z0-9\u4e00-\u9fa5]{2,10}$/
      if (!pathUsername.test(this.reg_con.username)) {
        this.common.showRegError('用户名为2-10位中英文和数字', _this)
        this.$refs.regUsername.focus()
        this.reg_con.username = ''
        return false
      }
      /** 验证手机号 */
      let pathPhone = /^1[34578]\d{9}$/
      if (!pathPhone.test(this.reg_con.phoneNumber)) {
        this.common.showRegError('手机号码格式有误', _this)
        this.$refs.regPhone.focus()
        this.reg_con.phoneNumber = ''
        return false
      }
      /** 验证手机验证码 */
      if (!parseInt(this.reg_con.phoneVcodeCon) || parseInt(this.reg_con.phoneVcodeCon) !== this.reg_con.phoneVcode) {
        this.common.showRegError('手机验证码填写有误', _this)
        this.$refs.regPhoneVcode.focus()
        this.reg_con.phoneVcodeCon = ''
        return false
      }
      /* 验证密码 */
      let pathPassword = /^[a-zA-Z\d_]{6,16}$/
      if (!pathPassword.test(this.reg_con.password)) {
        this.common.showRegError('密码为6-16位的数字、英文、下划线', _this)
        this.$refs.regPassword.focus()
        this.reg_con.password = ''
        return false
      }

      /** 向服务器发送注册请求 */
      this.$ajax({
        method: 'post',
        url: '/web/php/register.php',
        data: this.$qs.stringify({
          username: this.reg_con.username,
          password: this.reg_con.password,
          phoneNumber: this.reg_con.phoneNumber
        })
      }).then((data) => {
        let result = data.data
        let returnCode = result.returnCode
        let dataInfo = result.dataInfo
        switch (returnCode) {
          case 10010: // 注册成功
            this.show(true)
            // 清空注册框
            this.reg_con.username = '' // 注册用户名
            this.reg_con.phoneNumber = '' // 注册手机号码
            this.reg_con.imgVcodeCon = '' // 注册图形验证码
            this.reg_con.phoneVcodeCon = '' // 注册手机验证码
            this.reg_con.password = '' // 注册密码
            break
          case 10011: // 用户名为2-10位中英文和数字
            this.$refs.regUsername.focus()
            break
          case 10012: // 密码为6-16位的数字、英文、下划线
            this.$refs.regPassword.focus()
            break
          case 10013: // 该手机号码已注册
            this.$refs.regPhone.focus()
            break
        }
        if (dataInfo) {
          this.common.showRegError(dataInfo, _this, true)
        }
      })
    }
  },
  watch: {
    reg_conphoneNumber () { // 监听注册框内手机号码，如果手机号码合法则展示验证码框
      if (/^1[34578]\d{9}$/.test(this.reg_con.phoneNumber)) {
        this.vcodeShow = true
        this.reg_con.phoneVcode = ''
        this.changeImgVcode()
      } else {
        this.vcodeShow = false
      }
    },
    storeShowLogBox () {
      if (this.$store.state.showLogBox) {
        this.show(true)
      }
    }
  },
  computed: {
    reg_conphoneNumber () {
      return this.reg_con.phoneNumber
    },
    storeShowLogBox () {
      return this.$store.state.showLogBox
    }
  }
}

</script>
<style lang='stylus' scoped>
@import '~styles/varibles'

// 动画专区
.logbox-enter, .logbox-leave-to
  opacity 0
  margin-top 2rem
.logbox-enter-active, .logbox-leave-active
  transition all .3s

.auth-modal-box
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  z-index 500
  display flex
  align-items center
  justify-content center
  .ajaxErrorBox
    position absolute
    bottom 0
    left 0
    background #fff
  // .errorBox
  //   background #ffd2d2
  //   position absolute
  //   width 6.4rem
  //   max-width 100%
  //   max-height 2rem
  //   box-sizing border-box
  //   padding .2rem
  //   border-radius .1rem
  //   text-align center
  //   border .02rem solid red
  //   color red
  //   top -2rem
  //   opacity 0
  //   transition .5s
  //   &.show
  //     top 8%
  //     opacity 1
  //   &.succ
  //     background #d6ffd6
  //     color #16bb00
  //     border-color #21ff03
  .auth-form
    width 6.4rem
    padding .48rem
    box-sizing border-box
    border-radius .04rem
    background $theme-background
    position relative
    box-shadow 0px 4px 4px 0px rgba(0,0,0,0.3)
    .panda
      position absolute
      top -1.5rem
      left 2rem
      img
        width 2.4rem
    .close-btn
      float right
      font-size .24rem
      opacity .4
      cursor pointer
      &:after
        content '\e64f'
    .panel
      .title
        font-size .36rem
        font-weight bold
        margin-bottom .48rem
        line-height 1.3
      .input-group
        overflow hidden
        margin-bottom .12rem
        .input-box
          margin-bottom .2rem
          position relative
          &.vcode-box
            display flex
            justify-content center
            align-items center
            .input
              max-width 1.9rem
            .vcode-img
              width 3.2rem
              height 0.8rem
              background #68a7e7
              margin-left .3rem
              color #fff
              display flex
              justify-content center
              align-items center
              cursor pointer
              user-select none
          .send-vcode-btn
            color $theme-color
            position absolute
            right 0
            top 0
            background transparent
            padding 0 .32rem
            cursor pointer
            height 100%
            &.action
              color $theme-3-color
              cursor not-allowed
          .input
            border 1px solid #e9e9e9
            padding .2rem
            width 100%
            box-sizing border-box
            transition border-color .3s
            border-radius .04rem
            &:focus
              border-color #007fff
      .submit
        cursor pointer
        width 100%
        box-sizing border-box
        background $theme-color
        color #ffffff
        height .7rem
        border-radius .04rem
        &:hover
          background #0058b0
      .prompt-box
        margin-top .24rem
        color #8b9196
        &.center
          text-align center
        .clickable
          cursor pointer
          color $theme-color
          &.right
            float right
    .oauth-box
      margin-top .24rem
      line-height .44rem
      color #8b9196
      .oauth-btn
        cursor pointer
        box-sizing border-box
        width .72rem
        height 0.7rem
        background #ea3737
        color $theme-background
        margin-top .24rem
        white-space nowrap
        padding 0 .2rem
        border-radius .36rem
        transition all .5s
        overflow hidden
        &:before
          content: '\e60a'
          margin-right .2rem
        &:hover
          background #e51a1a
          width 100%

@media only screen and (max-width: 1024px)
  .auth-modal-box .auth-form .oauth-box .oauth-btn
    width 100%
</style>
